import React, { useState, useEffect } from 'react';
import { 
  Drawer, 
  List, 
  Button, 
  Typography, 
  Space, 
  Input,
  Tooltip,
  Popconfirm,
  message,
  Empty
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  MessageOutlined
} from '@ant-design/icons';
import { chatAPI } from '../services/api';
import dayjs from 'dayjs';

const { Text } = Typography;
const { Search } = Input;

const SessionSidebar = ({ 
  visible, 
  onClose, 
  currentSessionId, 
  onSessionSelect,
  onNewSession 
}) => {
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [deleteLoading, setDeleteLoading] = useState({});

  // 获取会话列表
  const fetchSessions = async (keyword = '') => {
    try {
      setLoading(true);
      const response = await chatAPI.getSessions(20, keyword || null);
      setSessions(response.sessions || []);
    } catch (error) {
      console.error('获取会话列表失败:', error);
      message.error('获取会话列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 搜索会话
  const handleSearch = (value) => {
    setSearchKeyword(value);
    fetchSessions(value);
  };

  // 删除会话
  const handleDeleteSession = async (sessionId) => {
    try {
      setDeleteLoading(prev => ({ ...prev, [sessionId]: true }));
      await chatAPI.deleteSession(sessionId);
      message.success('会话已删除');
      
      // 如果删除的是当前会话，创建新会话
      if (sessionId === currentSessionId) {
        onNewSession();
      }
      
      // 刷新会话列表
      fetchSessions(searchKeyword);
    } catch (error) {
      console.error('删除会话失败:', error);
      message.error('删除会话失败');
    } finally {
      setDeleteLoading(prev => ({ ...prev, [sessionId]: false }));
    }
  };

  // 格式化时间
  const formatTime = (time) => {
    const now = dayjs();
    const target = dayjs(time);
    
    if (now.diff(target, 'day') === 0) {
      return target.format('HH:mm');
    } else if (now.diff(target, 'day') === 1) {
      return '昨天';
    } else if (now.diff(target, 'week') === 0) {
      return target.format('dddd');
    } else {
      return target.format('MM-DD');
    }
  };

  // 截断标题
  const truncateTitle = (title, maxLength = 20) => {
    if (!title || title.length <= maxLength) {
      return title || '新对话';
    }
    return title.substring(0, maxLength) + '...';
  };

  useEffect(() => {
    if (visible) {
      fetchSessions();
    }
  }, [visible]);

  return (
    <Drawer
      title={
        <Space>
          <MessageOutlined />
          <span>对话历史</span>
        </Space>
      }
      placement="left"
      onClose={onClose}
      open={visible}
      width={320}
      extra={
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={onNewSession}
          size="small"
        >
          新对话
        </Button>
      }
    >
      {/* 搜索框 */}
      <div style={{ marginBottom: '16px' }}>
        <Search
          placeholder="搜索对话..."
          allowClear
          onSearch={handleSearch}
          onChange={(e) => {
            if (!e.target.value) {
              handleSearch('');
            }
          }}
          style={{ width: '100%' }}
        />
      </div>

      {/* 会话列表 */}
      <List
        loading={loading}
        dataSource={sessions}
        locale={{
          emptyText: (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="暂无对话记录"
            />
          )
        }}
        renderItem={(session) => (
          <List.Item
            style={{
              padding: '12px 0',
              cursor: 'pointer',
              backgroundColor: session.session_id === currentSessionId ? '#f6ffed' : 'transparent',
              borderRadius: '6px',
              marginBottom: '4px',
              border: session.session_id === currentSessionId ? '1px solid #b7eb8f' : '1px solid transparent'
            }}
            onClick={() => {
              onSessionSelect(session.session_id);
              onClose();
            }}
            actions={[
              <Popconfirm
                title="确定要删除这个对话吗？"
                description="删除后无法恢复"
                onConfirm={(e) => {
                  e.stopPropagation();
                  handleDeleteSession(session.session_id);
                }}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <Button
                  type="text"
                  danger
                  size="small"
                  icon={<DeleteOutlined />}
                  loading={deleteLoading[session.session_id]}
                  onClick={(e) => e.stopPropagation()}
                />
              </Popconfirm>
            ]}
          >
            <List.Item.Meta
              title={
                <Tooltip title={session.title || '新对话'}>
                  <Text strong={session.session_id === currentSessionId}>
                    {truncateTitle(session.title)}
                  </Text>
                </Tooltip>
              }
              description={
                <Space direction="vertical" size={2}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {formatTime(session.updated_at)}
                  </Text>
                  <Text 
                    type={session.status ? 'success' : 'secondary'} 
                    style={{ fontSize: '11px' }}
                  >
                    {session.status ? '活跃' : '已结束'}
                  </Text>
                </Space>
              }
            />
          </List.Item>
        )}
      />
    </Drawer>
  );
};

export default SessionSidebar;
